package com.atguigu.tingshu.order.strategy.Impl;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;

@Service
@Slf4j
public class AlbumOrderTradeStrategy implements OrderTradeStrategy {

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient ;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient ;

    @Autowired
    private RedisTemplate<String , String> redisTemplate ;

    @Override
    public OrderInfoVo trade(TradeVo tradeVo) {

        // 获取当前登录用户id
        Long userId = AuthContextHolder.getUserId();
        Long itemId = tradeVo.getItemId();          // 获取专辑id

        // 判断当前的用户是否购买过这个专辑，健壮性的判断
        Result<Boolean> paidAlbumResult = userInfoFeignClient.isPaidAlbum(itemId, userId);
        Boolean data = paidAlbumResult.getData();
        if(data) {
            throw new GuiguException(ResultCodeEnum.REPEAT_BUY_ERROR) ;
        }

        // 根据付款项目的id查询专辑数据
        Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfoById(itemId);
        AlbumInfo albumInfo = albumInfoResult.getData();

        // 创建一个OrderInfoVo对象，封装结算页所需要的数据
        OrderInfoVo orderInfoVo = new OrderInfoVo() ;
        orderInfoVo.setItemType(SystemConstant.ORDER_ITEM_TYPE_ALBUM);

        //  获取当前登录用户的id

        Result<UserInfo> userInfoResult = userInfoFeignClient.findByUserId(userId);
        UserInfo userInfo = userInfoResult.getData();

        // 设置相关的金额
        BigDecimal originalAmount = albumInfo.getPrice();
        orderInfoVo.setOriginalAmount(originalAmount);
        Integer isVip = userInfo.getIsVip();
        long vipExpireTime = userInfo.getVipExpireTime().getTime();
        if(isVip.equals(1) && vipExpireTime > System.currentTimeMillis()) {     // 是vip用户，并且没有过期

            BigDecimal vipDiscount = albumInfo.getVipDiscount();        // 获取vip用户的折扣
            if(vipDiscount.intValue() == -1) {      // 没有折扣
                orderInfoVo.setDerateAmount(new BigDecimal("0.00"));
                orderInfoVo.setOrderAmount(originalAmount);
            }else {     // 有折扣

                // 计算减免金额
                BigDecimal orderAmount = originalAmount.multiply(vipDiscount)
                        .multiply(new BigDecimal("10"))
                        .divide(new BigDecimal("10"), 2, BigDecimal.ROUND_HALF_UP);
                orderInfoVo.setDerateAmount(originalAmount.subtract(orderAmount));
                orderInfoVo.setOrderAmount(orderAmount);

            }

        }else {     // 是普通用户

            BigDecimal discount = albumInfo.getDiscount() ;     // 普通用户的折扣
            if(discount.intValue() == -1) {      // 没有折扣
                orderInfoVo.setDerateAmount(new BigDecimal("0.00"));
                orderInfoVo.setOrderAmount(originalAmount);
            }else {     // 有折扣

                // 计算减免金额
                BigDecimal orderAmount = originalAmount.multiply(discount)
                        .multiply(new BigDecimal("10"))
                        .divide(new BigDecimal("10"), 2, BigDecimal.ROUND_HALF_UP);
                orderInfoVo.setDerateAmount(originalAmount.subtract(orderAmount));
                orderInfoVo.setOrderAmount(orderAmount);

            }

        }

        // 构建明细数据
        OrderDetailVo orderDetailVo = new OrderDetailVo() ;
        orderDetailVo.setItemId(itemId);
        orderDetailVo.setItemName(albumInfo.getAlbumTitle());
        orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
        orderDetailVo.setItemPrice(orderInfoVo.getOrderAmount());
        orderInfoVo.setOrderDetailVoList(Arrays.asList(orderDetailVo));

        // 构建减免明细
        if(orderInfoVo.getDerateAmount().intValue() > 0) {
            OrderDerateVo orderDerateVo = new OrderDerateVo() ;
            orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
            orderDerateVo.setDerateAmount(orderInfoVo.getDerateAmount());
            orderDerateVo.setRemarks("专辑购买折扣");
            orderInfoVo.setOrderDerateVoList(Arrays.asList(orderDerateVo));
        }

        this.setOtherDataToOrderInfoVo(orderInfoVo , redisTemplate);

        // 返回
        return orderInfoVo;
    }

    @Override
    public String getItemType() {
        return SystemConstant.ORDER_ITEM_TYPE_ALBUM;        // 1001
    }

}
